import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    // 登陆页面
    { path: '/login', component: () => import('@/views/login/LoginPage.vue') },

    // 架子
    {
      path: '/',
      component: () => import('@/views/layout/DashboardLayout.vue'),
      redirect: '/rooms/RoomChannel',
      children: [
        {
          path: '/rooms/RoomChannel',
          component: () => import('@/views/room/RoomChannel.vue'),
        },
        {
          path: '/rooms/RoomManagement',
          component: () => import('@/views/room/RoomManagement.vue'),
        },
        {
          path: '/rooms/OrderManagement',
          component: () => import('@/views/room/OrderManagement.vue'),
        },
        {
          path: '/rooms/coupon',
          component: () => import('@/views/room/couponManage.vue'),
        },
        {
          path: '/comment/commentManagement',
          component: () => import('@/views/comment/commentPage.vue'),
        },
        {
          path: '/user/avatar',
          component: () => import('@/views/user/UserAvatar.vue'),
        },
        {
          path: '/user/profile',
          component: () => import('@/views/user/UserProfile.vue'),
        },
        {
          path: '/user/password',
          component: () => import('@/views/user/UserPassword.vue'),
        },
      ],
    },
  ],
})

// 返回值：
// 1. undefined / true  直接放行
// 2. false 拦回from的地址页面
// 3. 具体路径 或 路径对象  拦截到对应的地址
//    '/login'   { name: 'login' }
router.beforeEach((to) => {
  // 如果没有token, 且访问的是非登录页，拦截到登录，其他情况正常放行
  const useStore = useUserStore()
  if (!useStore.token && to.path !== '/login') return '/login'
})

export default router
